<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程编号" prop="classNumber">
        <el-input
          v-model="queryParams.classNumber"
          placeholder="请输入课程编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科任老师" prop="teacherId">
        <el-input
          v-model="queryParams.teacherId"
          placeholder="请输入科任老师"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程状态" prop="courseStatus">
        <el-select v-model="queryParams.courseStatus" placeholder="请选择课程状态" clearable>
          <el-option
            v-for="dict in course_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程分类" prop="courseTypeId">
        <el-select v-model="queryParams.courseTypeId" placeholder="请选择课程分类" clearable>
          <el-option
            v-for="dict in course_typelist"
            :key="dict.id"
            :label="dict.classTypeName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:course:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:course:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="id" width="100px" />
      <el-table-column label="课程编号" align="center" prop="classNumber" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="课程分类" align="center" prop="courseTypeId">
        <template #default="scope">
          <template v-for="item in course_typelist" :key="item.id">
            <span v-if="item.id === scope.row.courseTypeId">{{ item.classTypeName }}</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="科任老师" align="center" prop="teacherId" />
      <el-table-column label="课程状态" align="center" prop="courseStatus">
        <template #default="scope">
          <dict-tag :options="course_type" :value="scope.row.courseStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="课程的章节数" align="center" prop="numOfChapters" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:course:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:course:remove']">删除</el-button>
          <el-link link type="primary" icon="ZoomIn" @click="goToChapter(scope.row.id)">查看课程章节</el-link>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    
     <!-- 添加或修改课程展示对话框 -->
     <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="courseRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程编号" prop="classNumber">
          <el-input v-model="form.classNumber" placeholder="请输入课程编号" />
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="科任老师" prop="teacherId">
          <el-input v-model="form.teacherId" placeholder="请输入科任老师" />
        </el-form-item>
        <!-- <el-form-item label="课程章节" prop="numOfChapters">
          <el-input v-model="form.numOfChapters" placeholder="请输入课程的章节数" />
        </el-form-item> -->
        <el-form-item label="课程状态" prop="courseStatus">
          <el-select v-model="form.courseStatus" placeholder="请选择课程状态">
            <el-option
              v-for="dict in course_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程分类" prop="courseTypeId">
          <el-select v-model="form.courseTypeId" placeholder="请选择课程分类">
            <el-option
              v-for="dict in course_typelist"
              :key="dict.id"
              :label="dict.classTypeName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改课程展示对话框 -->
    <!-- <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="courseRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程编号" prop="classNumber">
          <el-input v-model="form.classNumber" placeholder="请输入课程编号" />
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="科任老师" prop="teacherId">
          <el-input v-model="form.teacherId" placeholder="请输入科任老师" />
        </el-form-item>
        <el-form-item label="课程状态" prop="courseStatus">
          <el-select v-model="form.courseStatus" placeholder="请选择课程状态">
            <el-option
              v-for="dict in course_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程分类" prop="courseTypeId">
          <el-select v-model="form.courseTypeId" placeholder="请选择课程分类">
            <el-option
              v-for="dict in course_typelist"
              :key="dict.id"
              :label="dict.classTypeName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        
manage:chapter:list  -->
 <!-- v-hasPermi="['manage:courseType:remove'] -->
        <!-- <div class="file-upload">
    <h2>头像上传</h2>
    <input type="file" @change="handleFileChange" /> -->

    <!-- <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="!selectedFile"
          @click="uploadFile"
          v-hasPermi="['manage:chapter:list']"
        >删除</el-button>
    
    <p v-if="uploadMessage" :class="{ success: isSuccess, error: !isSuccess }">{{ uploadMessage }}</p>
  </div> -->

        <!-- <div class="file-upload">
          <h2>头像上传</h2>
          <input type="file" @change="handleFileChange" />
          <button @click="uploadFile" :disabled="!selectedFile">上传</button>
          <p v-if="uploadMessage" :class="{ success: isSuccess, error: !isSuccess }">{{ uploadMessage }}</p>
        </div> -->
      <!-- </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup name="Course">
import { listCourse, getCourse, delCourse, addCourse, updateCourse } from "@/api/manage/course";
import {listCourseType} from "@/api/manage/courseType";
import { useRouter } from 'vue-router';
const { proxy } = getCurrentInstance();
const { course_type } = proxy.useDict('course_type');

// const { queryParams, form, rules } = toRefs(data);
const courseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// ----------------------------------------------
import { ref } from 'vue';


const selectedFile = ref(null);
const uploadMessage = ref('');
const isSuccess = ref(false);

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFile.value = file;
    uploadMessage.value = ''; // 清除以前的消息
  }
};

// const uploadFile = async (event) => {
//   event.preventDefault(); // 阻止默认行为
//   if (!selectedFile.value) return;

//   const formData = new FormData();
//   formData.append('file', selectedFile.value);

//   // 获取JWT令牌，这里假设你已经有一个方法来获取令牌，例如从Vuex、Context或其他全局状态管理库中
//   const token = localStorage.getItem('token'); // 或者从其他地方获取，如context、vuex等

//   try {
//     const response = await axios.post('/dev-api/common/uploadMinio', formData, {
//       headers: {
//         'Content-Type': 'multipart/form-data',
//         // 添加JWT令牌到请求头
//         'Authorization': `Bearer ${token}`
//       },
//     });

//     if (response.data.url) {
//       uploadMessage.value = '文件上传成功！';
//       isSuccess.value = true;
//     } else {
//       uploadMessage.value = '文件上传失败，请重试。';
//       isSuccess.value = false;
//     }
//   } catch (error) {
//     uploadMessage.value = '上传过程中出现错误，请稍后再试。';
//     isSuccess.value = false;
//   } finally {
//     selectedFile.value = null; // 上传完成后重置文件输入
//   }
// };

// const uploadFile = async (event) => {
//   event.preventDefault(); // 阻止默认行为
//   if (!selectedFile.value) return;

//   const formData = new FormData();
//   formData.append('file', selectedFile.value);

//   try {
//     const response = await axios.post('/dev-api/common/uploadMinio', formData, {
//       headers: {
//         'Content-Type': 'multipart/form-data',
//       },
//     });

//     if (response.data.url) {
//       uploadMessage.value = '文件上传成功！';
//       isSuccess.value = true;
//     } else {
//       uploadMessage.value = '文件上传失败，请重试。';
//       isSuccess.value = false;
//     }
//   } catch (error) {
//     uploadMessage.value = '上传过程中出现错误，请稍后再试。';
//     isSuccess.value = false;
//   } finally {
//     selectedFile.value = null; // 上传完成后重置文件输入
//   }
// };

//------------------------------------------------

const data = reactive({
  selectedFile: null,
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    classNumber: null,
    courseName: null,
    courseTypeId: null,
    teacherId: null,
    courseStatus: null,
  },
  rules: {
    classNumber: [
      { required: true, message: "课程编号不能为空", trigger: "blur" }
    ],
    courseName: [
      { required: true, message: "课程名称不能为空", trigger: "blur" }
    ],
    courseTypeId: [
      { required: true, message: "课程分类不能为空", trigger: "change" }
    ],
    teacherId: [
      { required: true, message: "科任老师不能为空", trigger: "blur" }
    ],
  }

    
});

const { queryParams, form, rules } = toRefs(data);

/** 查询课程展示列表 */
function getList() {
  loading.value = true;
  listCourse(queryParams.value).then(response => {
    courseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    classNumber: null,
    courseName: null,
    courseTypeId: null,
    teacherId: null,
    courseStatus: null,
    creatTime: null,
    updataTime: null,
    isDelete: null,
    numOfChapters: null
  };
  proxy.resetForm("courseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加课程展示";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCourse(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改课程展示";
  });
}



/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除课程展示编号为"' + _ids + '"的数据项？').then(function() {
    return delCourse(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/course/export', {
    ...queryParams.value
  }, `course_${new Date().getTime()}.xlsx`)
}
/**获取课程分类列表 */
const course_typelist = ref([]);
function getCourseTypeList() {
  listCourseType(queryParams.value).then(response => {
    course_typelist.value = response.rows;
    console.log(course_typelist.value);
  });
}
// /** 文件选择事件 */
// const onFileChange = (e) => {
//   const file = e.target.files[0];
//   if (file) {
//     data.selectedFile = file;
//   }
// };

/** 提交按钮 */
function submitForm() {
  proxy.$refs["courseRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

const router = useRouter();
/**查看课程章节 */
function goToChapter(id){
  console.log(id);
  router.push(
    {
      path: '/course/chapter',
      query: {
        courseId: id
      }
    }
  )
  
}

// /** 文件上传事件 */
// const uploadFile = () => {
//   if (!data.selectedFile) {
//     message.value = '请选择一个文件';
//     return;
//   }

//   const formData = new FormData();
//   formData.append('file', data.selectedFile);

//   axios.post('/file/upload', formData, {
//     headers: {
//       'Content-Type': 'multipart/form-data'
//     }
//   }).then(response => {
//     message.value = '文件上传成功';
//     console.log('文件上传响应:', response);
//     // 假设服务器返回了文件的路径或其他相关信息
//     form.fileUrl = response.data.fileUrl; // 假设返回的数据中包含 fileUrl 字段
//   }).catch(error => {
//     message.value = '文件上传失败';
//     console.error('文件上传错误:', error);
//   });
// };


getCourseTypeList();
getList();
</script>

<style scoped>
.file-upload {
  max-width: 400px;
  margin: auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.success {
  color: green;
}
.error {
  color: red;
}
</style>
